package homework;

import java.util.concurrent.Semaphore;

/**
 * 采用Semaphore
 */
public class Method05 {

    private final Semaphore semaphore = new Semaphore(1);
    //存储返回结果
    private volatile Integer value = null;

    private void sum(int num) {
        try {
            semaphore.acquire();
            value = fibo(num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }

    }

    private int fibo(int a) {
        if ( a < 2)
            return 1;
        return fibo(a-1) + fibo(a-2);
    }

    public int getValue() throws InterruptedException {
        //循环等待线程返回结果
        int res;
        try {
            semaphore.acquire();
            res = this.value;
        } finally {
            semaphore.release();
        }
        return res;
    }

    public static void main(String[] args) throws InterruptedException {

        long start=System.currentTimeMillis();

        Method05 method = new Method05();
        // 在这里创建一个线程或线程池，
        new Thread(() -> {
            method.sum(36);
        }).start();
        // 异步执行 下面方法
        //Thread.sleep(1000);
         //这是得到的返回值
        int result = method.getValue();
        // 确保  拿到result 并输出
        System.out.println("异步计算结果为：" + result);

        System.out.println("使用时间："+ (System.currentTimeMillis()-start) + " ms");
        // 然后退出main线程
    }



}
